package part3.c13_active_object;

/**
 * Created by lie on 2018/3/22.
 * 睡眠，直到{@link #millisecondsForSleep}结束，才会把{@link #wakeUpCommand}添加进引擎
 */
public class SleepCommand implements Command {

    private long millisecondsForSleep;
    private ActiveObjectEngine engine;
    private Command wakeUpCommand;

    private boolean isStarted = false;
    private long timeStartAtThisTime;

    public SleepCommand(long millisecondsForSleep, ActiveObjectEngine engine, Command wakeUpCommand) {
        this.millisecondsForSleep = millisecondsForSleep;
        this.engine = engine;
        this.wakeUpCommand = wakeUpCommand;
    }

    public void execute() throws Exception {

        if (!isStarted) {
            timeStartAtThisTime = System.currentTimeMillis();
            engine.addCommand(this);
            isStarted = true;
        } else if (System.currentTimeMillis() - timeStartAtThisTime < millisecondsForSleep) {
            engine.addCommand(this);
        } else {
            //把wakeUpCommand加进引擎
            engine.addCommand(wakeUpCommand);
//            isStarted = false;
        }

    }
}
